import dayjs from "dayjs";
import { useCallback } from "react";
import { useSearchParams } from "react-router-dom";

export type StatsParamsT = {
  startDate?: Date;
  endDate?: Date;
  batchEndDate?: string;
};

export const useStatsParams = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const startDate = dayjs(searchParams.get("startDate")).isValid()
    ? (dayjs(
        searchParams.get("startDate")
      ).toDate() as StatsParamsT["startDate"])
    : dayjs("2023-01-01").toDate();
  const endDate = dayjs(searchParams.get("endDate")).isValid()
    ? (dayjs(searchParams.get("endDate")).toDate() as StatsParamsT["endDate"])
    : dayjs(new Date()).toDate();
  const batchEndDate = searchParams.get("batchEndDate")
    ? (searchParams.get("batchEndDate") as StatsParamsT["batchEndDate"])
    : "%";

  const setStatsParams = useCallback((params: StatsParamsT) => {
    setSearchParams((values: any) => {
      if (params.startDate !== undefined) {
        values.set("startDate", params.startDate);
      }
      if (params.endDate !== undefined) {
        values.set("endDate", params.endDate);
      }
      if (params.batchEndDate !== undefined) {
        values.set("batchEndDate", params.batchEndDate);
      }
      return values;
    });
  }, []);

  return {
    startDate,
    endDate,
    batchEndDate,
    setStatsParams,
  };
};
